from duckserver.models import User
from duckserver.models import Todolist
import datetime
import time


# 创建代办清单
def createTodo(title, content, userid, endtime, alarmtime):
    response = {'todoid': 0, 'ok': 0, 'msg': ''}
    createtime = int(time.time())
    user = User.objects.get(userid=userid)
    todo = Todolist(title=title, content=content,
                    userid=user, endtime=endtime, alarmtime=alarmtime)
    todo.save()
    response['todoid'] = todo.todoid
    response["ok"] = 1
    return response

# 获取待办清单列表

def getTodoList(userid):
    response = {'data': [], 'ok': 0, 'msg': ''}

    todos = Todolist.objects.filter(userid_id=userid)
    now = time.time()
    for todo in todos:
        obj = {}
        obj['todoid'] = todo.todoid
        obj['title'] = todo.title
        obj['content'] = todo.content
        obj['createtime'] = todo.createtime
        obj['endtime'] = todo.endtime
        obj['finishtime'] = todo.finishtime
        obj['alarmtime'] = todo.alarmtime
        obj['isfinished'] = todo.isfinished
        # 任务超时判断
        if todo.isfinished == 0 and time.mktime(todo.endtime.timetuple()) < now:
            obj['isfinished'] = -1
            todo.isfinished = -1
            todo.save()
        response['data'].append(obj)

    response["ok"] = 1
    return response

# 完成待办


def finishTodo(todoid, isfinished):
    response = {'todoid': 0, 'ok': 0, 'msg': ''}
    todo = Todolist.objects.get(todoid=todoid)
    finishtime = int(time.time())
    todo.isfinished = isfinished
    todo.finishtime = timestamp2string(finishtime)
    todo.save()

    response['todoid'] = todo.todoid
    response['ok'] = 1

    return response

# 删除待办


def deleteTodo(userid, todoid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    todo = Todolist.objects.get(todoid=todoid, userid=user)
    response['todoid'] = todo.todoid

    todo.delete()

    response['ok'] = 1
    return response


def timestamp2string(timeStamp):
    try:
        d = datetime.datetime.fromtimestamp(int(timeStamp))
        str1 = d.strftime("%Y-%m-%d %H:%M:%S")
        # 2015-08-28 16:43:37'
        return str1
    except Exception as e:
        print(e)
        return ''
